<template>
  <div class="activities-page">
    <el-card class="page-card">
      <template #header>
        <div class="card-header">
          <h2>我参与的活动</h2>
        </div>
      </template>

      <!-- 筛选栏 -->
      <div class="filter-bar mb-4">
        <el-input
          v-model="searchKeyword"
          placeholder="搜索活动"
          class="search-input"
          clearable
          @clear="handleSearch"
          @keyup.enter="handleSearch"
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>

        <el-select
          v-model="filterType"
          placeholder="活动类型"
          @change="handleFilterChange"
        >
          <el-option label="全部" value="" />
          <el-option label="文化活动" value="culture" />
          <el-option label="旅游活动" value="travel" />
          <el-option label="美食节" value="food" />
          <el-option label="摄影展" value="photo" />
          <el-option label="展览展会" value="exhibition" />
        </el-select>

        <el-select
          v-model="filterStatus"
          placeholder="活动状态"
          @change="handleFilterChange"
        >
          <el-option label="全部" value="" />
          <el-option label="报名中" value="registering" />
          <el-option label="进行中" value="ongoing" />
          <el-option label="已结束" value="ended" />
        </el-select>

        <el-select
          v-model="sortBy"
          placeholder="排序方式"
          @change="handleSortChange"
        >
          <el-option label="最近活动" value="latest" />
          <el-option label="最早活动" value="earliest" />
          <el-option label="最多参与" value="participants" />
        </el-select>
      </div>

      <!-- 活动列表 -->
      <div class="activities-list" v-loading="loading">
        <div
          v-for="activity in paginatedActivities"
          :key="activity.id"
          class="activity-item"
        >
          <div class="activity-cover" v-if="activity.coverImage">
            <el-image
              :src="activity.coverImage"
              fit="cover"
              :preview-src-list="[activity.coverImage]"
            />
          </div>
          <div class="activity-main">
            <div class="activity-title">
              <el-tag
                size="small"
                :type="getTagType(activity.status)"
                class="mr-2"
              >
                {{ getStatusText(activity.status) }}
              </el-tag>
              <el-tag size="small" type="info" class="mr-2">
                {{ getTypeText(activity.type) }}
              </el-tag>
              <router-link :to="'/activity/' + activity.id" class="title-link">
                {{ activity.title }}
              </router-link>
            </div>
            <div class="activity-info">
              <div class="info-item">
                <el-icon><Calendar /></el-icon>
                <span
                  >{{ formatDate(activity.startTime) }} -
                  {{ formatDate(activity.endTime) }}</span
                >
              </div>
              <div class="info-item">
                <el-icon><Location /></el-icon>
                <span>{{ activity.location }}</span>
              </div>
              <div class="info-item">
                <el-icon><User /></el-icon>
                <span>{{ activity.organizer }}</span>
              </div>
            </div>
            <div class="activity-content">{{ activity.description }}</div>
            <div class="activity-meta">
              <div class="meta-left">
                <span class="meta-item">
                  <el-icon><UserFilled /></el-icon>
                  {{ activity.participantsCount }} 人参与
                </span>
                <span class="meta-item">
                  <el-icon><Star /></el-icon>
                  {{ activity.favoriteCount }} 人收藏
                </span>
                <span class="meta-item">
                  <el-icon><ChatDotRound /></el-icon>
                  {{ activity.commentCount }} 条评论
                </span>
              </div>
              <div class="meta-right">
                <el-button-group>
                  <el-button
                    type="primary"
                    link
                    @click="viewActivity(activity)"
                  >
                    <el-icon><View /></el-icon>
                    查看
                  </el-button>
                  <el-button
                    type="danger"
                    link
                    @click="cancelParticipation(activity)"
                    v-if="activity.status === 'registering'"
                  >
                    <el-icon><Close /></el-icon>
                    取消报名
                  </el-button>
                </el-button-group>
              </div>
            </div>
          </div>
        </div>

        <!-- 空状态 -->
        <el-empty
          v-if="!loading && paginatedActivities.length === 0"
          description="暂无参与的活动"
        />
      </div>

      <!-- 分页 -->
      <div class="pagination-wrapper">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :total="total"
          :page-sizes="[10, 20, 30, 50]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from "vue";
import { useRouter } from "vue-router";
import { ElMessage, ElMessageBox } from "element-plus";
import {
  Search,
  Calendar,
  Location,
  User,
  UserFilled,
  Star,
  ChatDotRound,
  View,
  Close,
} from "@element-plus/icons-vue";
import service from "@/api/axios";

const router = useRouter();

// 状态变量
const loading = ref(false);
const searchKeyword = ref("");
const filterType = ref("");
const filterStatus = ref("");
const sortBy = ref("latest");
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);

// 测试数据，API请求失败时使用
const mockActivities = [
  {
    id: 1,
    title: "2024贵港非物质文化遗产展演活动",
    description: "展示贵港地区非物质文化遗产，包括传统工艺、民间艺术等多个领域的精彩表演和展示，参与互动体验可获赠传统手工艺纪念品。",
    type: "culture",
    status: "registering",
    coverImage: "https://tse3-mm.cn.bing.net/th/id/OIP-C.YkHSuolnRGnTcslp1vomrgHaE8?w=261&h=180&c=7&r=0&o=7&cb=iwp2&pid=1.7&rm=3",
    startTime: "2024-06-15 09:00:00",
    endTime: "2024-06-15 17:00:00",
    location: "贵港市文化中心",
    organizer: "贵港市文化旅游局",
    participantsCount: 328,
    favoriteCount: 152,
    commentCount: 86,
  },
  {
    id: 2,
    title: "荷城古镇民俗文化节",
    description: "体验贵港荷城古镇传统民俗文化，品尝地道美食，感受古镇魅力。活动期间，古镇内景点门票五折优惠，并免费提供传统服饰体验。",
    type: "travel",
    status: "ongoing",
    coverImage: "https://tse1-mm.cn.bing.net/th/id/OIP-C.Ad6ihvkpeI9Id8g4zA3E5AHaDN?w=348&h=151&c=7&r=0&o=7&cb=iwp2&pid=1.7&rm=3",
    startTime: "2024-05-20 10:00:00",
    endTime: "2024-05-22 22:00:00",
    location: "贵港荷城古镇",
    organizer: "贵港市旅游局",
    participantsCount: 2341,
    favoriteCount: 423,
    commentCount: 187,
  },
  {
    id: 3,
    title: "贵港桂剧艺术周末专场",
    description: "每周末在贵港市文化艺术中心举办的桂剧展演活动，邀请知名桂剧团体进行精彩演出，并有机会与艺术家互动交流。",
    type: "exhibition",
    status: "upcoming",
    coverImage: "https://tse2-mm.cn.bing.net/th/id/OIP-C.7BqgXsW93eUd3jGCLfC93gHaEK?w=319&h=180&c=7&r=0&o=7&cb=iwp2&pid=1.7&rm=3",
    startTime: "2024-05-18 14:30:00",
    endTime: "2024-05-18 20:30:00",
    location: "贵港市文化艺术中心",
    organizer: "贵港市桂剧团",
    participantsCount: 182,
    favoriteCount: 94,
    commentCount: 53,
  },
];

// 活动列表
const activitiesList = ref([]);

// 获取用户参与的活动列表
const getActivitiesList = async () => {
  loading.value = true;
  try {
    // 调用获取用户参与活动列表的API
    const response = await service.get("/user/events", {
      params: {
        keyword: searchKeyword.value,
        type: filterType.value,
        status: filterStatus.value,
        sortBy: sortBy.value
      }
    });
    
    console.log("后端返回的用户活动数据:", response);
    
    // 处理后端返回的数据
    const activitiesData = response && response.data ? response.data : [];
    
    if (activitiesData && activitiesData.length > 0) {
      // 处理后端返回的数据
      activitiesList.value = activitiesData.map(activity => ({
        ...activity,
        // 确保字段格式一致
        type: activity.type || "其他活动",
        // 处理图片路径
        coverImage: activity.image || activity.coverImage || "/images/activities/default.jpg",
        // 确保必要字段存在
        participantsCount: activity.participantsCount || 0,
        favoriteCount: activity.favoriteCount || 0,
        commentCount: activity.commentCount || 0,
        // 格式化日期(如果需要)
        startTime: activity.startTime,
        endTime: activity.endTime,
        // 确保组织者信息存在
        organizer: activity.organizer || "贵港文化旅游局"
      }));
      
      // 更新总数
      total.value = activitiesList.value.length;
      console.log("处理后的用户活动数据:", activitiesList.value);
    } else {
      console.log("后端返回的数据为空，使用测试数据");
      // 如果后端没有数据或返回空数组，使用测试数据
      activitiesList.value = [...mockActivities];
      total.value = mockActivities.length;
    }
  } catch (error) {
    console.error("获取参与活动列表失败:", error);
    // 出错时使用测试数据
    activitiesList.value = [...mockActivities];
    total.value = mockActivities.length;
  } finally {
    loading.value = false;
  }
};

// 处理搜索
const handleSearch = () => {
  currentPage.value = 1;
  getActivitiesList();
};

// 处理筛选变化
const handleFilterChange = () => {
  currentPage.value = 1;
  getActivitiesList();
};

// 处理排序变化
const handleSortChange = () => {
  currentPage.value = 1;
  getActivitiesList();
};

// 处理页码变化
const handleCurrentChange = (page) => {
  currentPage.value = page;
  // 由于API不支持分页，我们在前端处理分页
};

// 处理每页条数变化
const handleSizeChange = (size) => {
  pageSize.value = size;
  currentPage.value = 1;
  // 由于API不支持分页，我们在前端处理分页
};

// 查看活动
const viewActivity = (activity) => {
  router.push({
    path: `/community/event/${activity.id}`,
    query: { from: 'user-activities' }
  });
};

// 取消报名
const cancelParticipation = async (activity) => {
  try {
    await ElMessageBox.confirm("确定要取消报名该活动吗？", "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    });
    
    loading.value = true;
    
    try {
      // 调用取消报名API
      await service.delete(`/user/events/${activity.id}`);
      ElMessage.success("已取消报名");
      
      // 重新获取列表
      getActivitiesList();
    } catch (error) {
      console.error("API取消报名失败:", error);
      
      // 模拟取消成功（仅在开发阶段使用）
      const index = activitiesList.value.findIndex(item => item.id === activity.id);
      if (index !== -1) {
        activitiesList.value.splice(index, 1);
        total.value -= 1;
      }
      ElMessage.success("已取消报名");
    }
  } catch (error) {
    if (error !== "cancel") {
      console.error("取消报名失败:", error);
    }
  } finally {
    loading.value = false;
  }
};

// 获取状态标签类型
const getTagType = (status) => {
  const typeMap = {
    registering: "success",
    ongoing: "warning",
    ended: "info",
  };
  return typeMap[status] || "info";
};

// 获取状态文本
const getStatusText = (status) => {
  const textMap = {
    registering: "报名中",
    ongoing: "进行中",
    ended: "已结束",
  };
  return textMap[status] || "未知";
};

// 获取类型文本
const getTypeText = (type) => {
  const textMap = {
    culture: "文化活动",
    travel: "旅游活动",
    food: "美食节",
    photo: "摄影展",
    exhibition: "展览展会",
  };
  return textMap[type] || "其他";
};

// 格式化日期
const formatDate = (date) => {
  return new Date(date).toLocaleString();
};

// 计算当前页数据
const paginatedActivities = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value;
  const end = start + pageSize.value;
  return activitiesList.value.slice(start, end);
});

onMounted(() => {
  getActivitiesList();
});
</script>

<style lang="scss" scoped>
.activities-page {
  .page-card {
    @apply bg-white dark:bg-gray-800 rounded-lg shadow-sm;

    :deep(.el-card__header) {
      @apply p-0 border-b border-gray-100 dark:border-gray-700;

      .card-header {
        @apply px-6 py-4 flex items-center justify-between;

        h2 {
          @apply text-lg font-medium text-gray-900 dark:text-white;
        }
      }
    }
  }

  .filter-bar {
    @apply flex items-center gap-4;

    .search-input {
      @apply w-64;
    }
  }

  .activities-list {
    @apply space-y-4;

    .activity-item {
      @apply flex items-start p-4 bg-gray-50 dark:bg-gray-800 rounded-lg hover:bg-gray-100 dark:hover:bg-gray-700 transition-colors duration-300;

      .activity-cover {
        @apply w-48 h-32 rounded-lg overflow-hidden mr-4 flex-shrink-0;

        :deep(.el-image) {
          @apply w-full h-full;
        }
      }

      .activity-main {
        @apply flex-1 min-w-0;

        .activity-title {
          @apply flex items-center flex-wrap mb-2;

          .title-link {
            @apply text-gray-900 dark:text-white font-medium hover:text-primary-600 dark:hover:text-primary-400 transition-colors duration-300;
          }
        }

        .activity-info {
          @apply flex flex-wrap gap-4 mb-2;

          .info-item {
            @apply flex items-center text-sm text-gray-600 dark:text-gray-300;

            .el-icon {
              @apply mr-1;
            }
          }
        }

        .activity-content {
          @apply text-sm text-gray-500 dark:text-gray-400 mb-3 line-clamp-2;
        }

        .activity-meta {
          @apply flex items-center justify-between;

          .meta-left {
            @apply flex items-center gap-4;

            .meta-item {
              @apply flex items-center text-sm text-gray-500 dark:text-gray-400;

              .el-icon {
                @apply mr-1;
              }
            }
          }
        }
      }
    }
  }

  .pagination-wrapper {
    @apply flex justify-center mt-6;
  }
}
</style>
